from time import sleep

from selenium.common import NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
from frp_page_object.base_page import BasePage, logger


class LoginPageFrp(BasePage):
    url = r'https://lstest.kukahome.com/'
    loc_name = (By.ID, 'usercode')
    loc_password = (By.ID, 'passwd')
    loc_login = (By.XPATH, '//*[@id="loginForm"]//button')
    loc_agreement = (By.XPATH, '//*[contains(text(),"阅读并同意")]/../input')
    loc_succeed = (By.XPATH, '//*[contains(text(),"确定")]')
    loc_failed = (By.XPATH, '//*[contains(text(),"！")]')

    def open(self):
        self.get(self.url)

    def input_name(self, name):
        sleep(1)  # 不能删
        self.input(self.loc_name, name)

    def input_password(self, password):
        self.input(self.loc_password, password)

    def click_login(self):
        self.click(self.loc_agreement)
        self.click(self.loc_login)

    def login(self, name='admin', password='kuka2020'):
        self.input_name(name)
        self.input_password(password)
        self.click_login()
        sleep(1)

    # 检查是否登录成功
    def check_login(self):
        try:
            self.locator(self.loc_failed, 3)
        except NoSuchElementException or TimeoutException:
            try:
                self.locator(self.loc_succeed, 15)
            except NoSuchElementException or TimeoutException:
                logger.error('零售系统登录失败')
                return False
            else:
                return True
        else:
            return False
